package com.example.demo.service;
import com.example.demo.dao.DrugsMapper;
import com.example.demo.dao.SaleMapper;
import com.example.demo.entity.CommonResult;
import com.example.demo.entity.Salesrecord;
import com.example.demo.entity.drugs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;


@Slf4j
@Service
public class SalesrecordService implements SaleDrugsimpl {

    @Autowired
    SaleMapper saleMapper;
    @Override
    public CommonResult addSalesrecord(Salesrecord salesrecord) {
        log.info(salesrecord.getDrug_id().trim());
        List<drugs> d01 = saleMapper.selectdrug(salesrecord.getDrug_id().trim());
      if (d01.size()>0){
          drugs drugs = d01.get(0);
          Integer amount = drugs.getAmount();
          String price =drugs.getPrice();
          String[] after = price.split("[元]");
          Integer s = Integer.valueOf(after[0]);
          if (salesrecord.getBuy_num()<=amount && salesrecord.getBuy_num()!=0){
              int i = saleMapper.UpdateAmount(amount - salesrecord.getBuy_num(),drugs.getDrug_id());
              if (i>0){
                  int i1 = saleMapper.AddSales_record(salesrecord);
                  if (i1>0){
                      Integer allprice=s*salesrecord.getBuy_num();
                      return new CommonResult(200, "添加成功","购买总价格:"+allprice);
                  }
                  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                  return new CommonResult(200, "添加失败");
              }
          }
          return new CommonResult(201, "仓库药品数量不足");
      }
        return new CommonResult(201, "没有此药品，请检查药品id是否输错");

    }

    @Override
    public CommonResult addReturn_drugs(Salesrecord salesrecord) {
        List<drugs> d01 = saleMapper.selectdrug(salesrecord.getDrug_id().trim());
        if (d01.size()>0){
            drugs drugs = d01.get(0);
            Integer amount = drugs.getAmount();
            String price =drugs.getPrice();
            int i = saleMapper.UpdateAmount(amount +salesrecord.getBuy_num(),drugs.getDrug_id());
            if (i>0){
                int i1 = saleMapper.addReturn_drugs(salesrecord);
                if (i1>0){
                    String[] after = price.split("[元]");
                    Integer s = Integer.valueOf(after[0]);
                    Integer allprice=s*salesrecord.getBuy_num();
                    return new CommonResult(200, "退货成功","退药总价格:"+allprice);
                    }
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new CommonResult(200, "退货失败");
                }
        }
        return new CommonResult(201, "没有此药品，请检查药品id是否输错");
    }
}
